<template>
  <div class="app-container scenic-detail">
    <!-- 返回按钮 -->
    <el-page-header

      @back="$router.go(-1)"
      class="page-header"
    />

    <el-card v-loading="loading" class="detail-card">
      <!-- 文章式主体内容 -->
      <div class="article-container">
        <!-- 标题区（最顶部） -->
        <div class="article-header">
          <h1 class="main-title">{{ scenic.name }}</h1>

          <div class="meta-info">
            <el-tag type="primary" class="type-tag">{{ scenic.type || '自然景观' }}</el-tag>
            <div class="basic-info">
              <span class="location">
                <i class="el-icon-location"></i>
                {{ scenic.address || '未提供地址' }}
              </span>
              <span v-if="scenic.openingHours" class="opening-time">
                <i class="el-icon-time"></i>
                {{ scenic.openingHours }}
              </span>
            </div>
          </div>
        </div>

        <!-- 图片区（标题下方，简介上方） -->
        <div v-if="parsedImages.length" class="image-section">
          <el-carousel
            height="400px"
            :autoplay="true"
            :interval="5000"
            @change="handleCarouselChange"
          >
            <el-carousel-item v-for="(img, index) in parsedImages" :key="index">
              <image-preview
                :src="img"
                :width="'100%'"
                :height="400"
                @click="viewImage(img)"
              >
                <img
                  :src="img"
                  class="carousel-image"
                  alt="景区图片"
                >
              </image-preview>
            </el-carousel-item>
          </el-carousel>

          <!-- 图片缩略图导航 -->
          <div class="image-thumbnails">
            <div
              v-for="(img, index) in parsedImages"
              :key="index"
              class="thumbnail"
              :class="{ active: currentIndex === index }"
              @click="switchImage(index)"
            >
              <img :src="getImageUrl(img)" :alt="`景区图片 ${index+1}`">
            </div>
          </div>
        </div>

        <!-- 内容区（简介及其他信息） -->
        <div class="content-section">
          <el-divider content-position="left"><h3>景区简介</h3></el-divider>
          <div class="intro-content" v-html="formatContent(scenic.intro || '暂无景区简介')"></div>

          <el-divider content-position="left" v-if="scenic.features"><h3>景区特色</h3></el-divider>
          <div class="features-content" v-if="scenic.features" v-html="formatContent(scenic.features)"></div>

          <el-divider content-position="left" v-if="scenic.tips"><h3>游玩贴士</h3></el-divider>
          <div class="tips-content" v-if="scenic.tips">
            <div class="tips-inner" v-html="formatContent(scenic.tips)"></div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getArea } from "@/api/system/area";
import imagePreview from "@/components/ImagePreview";

export default {
  name: "ScenicDetail",
  components: {
    imagePreview
  },
  data() {
    return {
      loading: true,
      scenic: {},
      parsedImages: [], // 处理后的图片URL
      currentIndex: 0, // 当前图片索引
      baseUrl: process.env.VUE_APP_BASE_API || ""
    };
  },
  mounted() {
    this.fetchData();
    console.log(this.$route.params.id)
  },
  methods: {
    // 获取景区详情
    async fetchData() {
      try {
        const id = this.$route.params.id;
        if (!id) {
          this.$message.error("参数错误");
          return this.$router.push("/scenic");
        }

        const response = await getArea(id);
        this.scenic = response.data;
        this.parseImages(); // 解析图片
      } catch (error) {
        console.error("获取景区详情失败:", error);
        this.$message.error("获取景区详情失败");
        setTimeout(() => this.$router.push("/scenic"), 2000);
      } finally {
        this.loading = false;
      }
    },

    // 解析图片URL
    parseImages() {
      const rawUrls = this.scenic.imageUrl;
      this.parsedImages = rawUrls
        .split(",")
        .map(url => url.trim())
        .filter(url => url)
    },

    // 处理图片路径
    getImageUrl(url) {
      if (!url){
        console.log('传进来的图片路径是null')
        return "";
      }
      // 若URL已包含完整协议（http/https），直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      // 否则拼接基础路径（处理相对路径）
      // 避免重复添加斜杠（如baseUrl以/结尾，url以/开头时只保留一个）
      const finalUrl =  this.baseUrl + (this.baseUrl.endsWith('/') ? '' : '/') +
          (url.startsWith('/') ? url.substring(1) : url);
      console.log("传进来的图片最终url是：" + finalUrl);
      return finalUrl;
    },

    // 查看大图
    viewImage(url) {
      this.$refs.imagePreview?.showLargeImage(url);
    },

    // 切换图片
    switchImage(index) {
      this.currentIndex = index;
    },

    // 轮播图切换时同步索引
    handleCarouselChange(index) {
      this.currentIndex = index;
    },

    // 格式化内容（处理换行和段落）
    formatContent(content) {
      if (!content) return "";
      // 将换行转为段落，保留排版
      return content
        .replace(/\n\n+/g, '</p><p>') // 空行分隔段落
        .replace(/\n/g, '<br>') // 单行换行
        .replace(/^/, '<p>') // 开头加p标签
        .replace(/$/, '</p>'); // 结尾加p标签
    }
  }
};
</script>

<style lang="scss" scoped>
.scenic-detail {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;

  .detail-card {
    border: none;
    box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
    border-radius: 8px;
    overflow: hidden;
  }

  .article-container {
    padding: 30px;

    // 标题区
    .article-header {
      text-align: center;
      margin-bottom: 30px;

      .main-title {
        font-size: 32px;
        color: #2c3e50;
        margin-bottom: 15px;
        line-height: 1.3;
        font-weight: 600;
      }

      .meta-info {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 10px;

        .type-tag {
          padding: 5px 18px;
          font-size: 14px;
          background-color: #f0f7ff;
          color: #1890ff;
          border-color: #e6f7ff;
        }

        .basic-info {
          color: #666;
          font-size: 14px;
          display: flex;
          flex-wrap: wrap;
          justify-content: center;
          gap: 20px;

          i {
            margin-right: 5px;
            font-size: 15px;
          }
        }
      }
    }

    // 图片区（标题下方，简介上方）
    .image-section {
      margin-bottom: 40px;
      border-radius: 8px;
      overflow: hidden;

      .carousel-image {
        width: 100%;
        height: 400px;
        object-fit: cover;
        transition: transform 0.3s ease;

        &:hover {
          transform: scale(1.01); // 轻微放大，增强交互感
        }
      }

      .image-thumbnails {
        display: flex;
        gap: 10px;
        margin-top: 15px;
        overflow-x: auto;
        padding-bottom: 5px; // 避免滚动条遮挡

        .thumbnail {
          width: 100px;
          height: 70px;
          border: 2px solid transparent;
          border-radius: 4px;
          overflow: hidden;
          cursor: pointer;
          transition: all 0.2s;

          &.active {
            border-color: #1890ff;
            box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
          }

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          &:hover {
            transform: translateY(-3px);
          }
        }
      }
    }

    // 内容区（简介及以下）
    .content-section {
      color: #333;
      font-size: 16px;
      line-height: 2; // 行高放大，提升阅读体验

      .el-divider {
        margin: 30px 0;

        & > h3 {
          font-size: 20px;
          color: #2c3e50;
          font-weight: 500;
        }
      }

      p {
        margin-bottom: 20px;
        text-align: justify; // 两端对齐，更美观
      }

      br {
        margin: 8px 0;
      }

      // 贴士区域样式
      .tips-content {
        margin: 15px 0 30px;

        .tips-inner {
          background-color: #fff8e6;
          padding: 20px;
          border-radius: 6px;
          border-left: 4px solid #faad14;
        }
      }
    }
  }
}

// 响应式调整
@media (max-width: 768px) {
  .scenic-detail {
    padding: 15px;

    .article-container {
      padding: 20px 15px;

      .article-header {
        .main-title {
          font-size: 26px;
        }

        .basic-info {
          gap: 15px;
          flex-direction: column;
          align-items: center;
        }
      }

      .image-section {
        .carousel-image {
          height: 280px; // 移动端图片高度减小
        }

        .image-thumbnails {
          .thumbnail {
            width: 80px;
            height: 60px;
          }
        }
      }

      .content-section {
        font-size: 15px;
        line-height: 1.8;

        .el-divider > h3 {
          font-size: 18px;
        }
      }
    }
  }
}
</style>
